package com.harsom.camerademo

import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.media.MediaRecorder
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.support.v7.app.AppCompatActivity
import android.util.DisplayMetrics
import android.view.View
import android.view.WindowManager
import android.widget.RelativeLayout
import android.widget.Toast
import com.harsom.camerademo.widgets.CameraGLSurfaceView
import com.yuri.xlog.XLog
import kotlinx.android.synthetic.main.activity_camera.*
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

class CameraActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //全屏
        window.setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
                WindowManager.LayoutParams. FLAG_FULLSCREEN)

        setContentView(R.layout.activity_camera)
        supportActionBar?.hide()

        //保持亮屏
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            val attributes = window.attributes
            attributes.systemUiVisibility = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            window.attributes = attributes

            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        }

        // Activity启动后就锁定为启动时的方向
        when (resources.configuration.orientation) {
            Configuration.ORIENTATION_PORTRAIT -> requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            Configuration.ORIENTATION_LANDSCAPE -> requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            else -> {
            }
        }

        XLog.d()

        val metrics = DisplayMetrics()
        windowManager.defaultDisplay.getRealMetrics(metrics)
        XLog.d("width:${metrics.widthPixels},height:${metrics.heightPixels}")
        MyApplication.mScreenWidth = metrics.widthPixels
        MyApplication.mScreenHeight = metrics.heightPixels

        glSurfaceView.setCallBack(object : CameraGLSurfaceView.CameraCallBack {
            override fun onSurfaceCreate() {
                runOnUiThread {
                    CameraInterface.instance.getCameraAngle(this@CameraActivity)

                    val rate = CameraInterface.instance.getPreviewRate()
                    XLog.d("rate:$rate")
                    val layoutParams = glSurfaceView.layoutParams as RelativeLayout.LayoutParams
                    layoutParams.width = MyApplication.mScreenWidth
                    layoutParams.height = (MyApplication.mScreenWidth * rate).toInt()

                    if (MyApplication.mScreenWidth > MyApplication.mScreenHeight) {
                        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL)
                    } else {
                        layoutParams.addRule(RelativeLayout.CENTER_VERTICAL)
                    }

                    XLog.d("layout.width:${layoutParams.width},height:${layoutParams.height}")
                    glSurfaceView.layoutParams = layoutParams
                }
            }
        })

        imageViewCapture.setOnClickListener {
            startCapture()
        }

        imageViewSwitch.setOnClickListener {
            glSurfaceView.switchCamera()
            CameraInterface.instance.getCameraAngle(this)
        }

        imageViewVideoRecord.setOnClickListener {
            if (mIsRecording) {
                stopRecorder()
            } else {
                startRecorder()
            }
        }
    }

    private fun startCapture() {
        CameraInterface.instance.takePicture()
    }


    //////////////recorder
    private var mMediaRecorder: MediaRecorder? = null
    private var filePath: String? = null
    private var mIsRecording = false

    private fun startRecorder() {
        CameraInterface.instance.getCamera()?.unlock()

        mMediaRecorder = MediaRecorder()
        mMediaRecorder!!.setOrientationHint(0)
        mMediaRecorder!!.setCamera(CameraInterface.instance.getCamera())
        mMediaRecorder!!.setAudioSource(MediaRecorder.AudioSource.MIC)
        mMediaRecorder!!.setVideoSource(MediaRecorder.VideoSource.CAMERA)
        mMediaRecorder!!.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
        mMediaRecorder!!.setVideoEncoder(MediaRecorder.VideoEncoder.H264)
        mMediaRecorder!!.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
        mMediaRecorder!!.setVideoSize(1920, 1080)
        mMediaRecorder!!.setVideoEncodingBitRate(2 * 1024 * 1024)// 设置帧频率，然后就清晰了
        mMediaRecorder!!.setVideoFrameRate(20)
        val date = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(Date())
        val fileName = "VID_$date.mp4"
        filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).toString() + "/" + fileName
        mMediaRecorder!!.setOutputFile(filePath)

        try {
            mMediaRecorder!!.prepare()
            mMediaRecorder!!.start()

            imageViewVideoRecord.setImageResource(R.drawable.ic_record_pressed)
            mIsRecording = true
        } catch (e: IOException) {
            e.printStackTrace()
        }

    }

    private fun stopRecorder() {
        if (mMediaRecorder != null) {
            mMediaRecorder!!.stop()
        }

        mIsRecording = false

        val scanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        scanIntent.data = Uri.fromFile(File(filePath!!))
        sendBroadcast(scanIntent)

        Toast.makeText(applicationContext, "已保存到:" + filePath!!, Toast.LENGTH_SHORT).show()
        imageViewVideoRecord.setImageResource(R.drawable.ic_record_normal)
    }

    override fun onResume() {
        super.onResume()
        //后台切换到前台，重新打开Camera
        glSurfaceView.onResume()
    }

    override fun onPause() {
        super.onPause()
        //前台切换到后台，关闭Camera
        glSurfaceView.onPause()
    }

}
